package mya.mes.mdc.internal.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import mya.common.jaxrs.base.JsonCallback;
import mya.common.jaxrs.op.OpGet;
import mya.common.jaxrs.result.ListResult;
import mya.common.jpa.context.AbstractQuery;
import mya.common.jpa.context.ServiceContext;
import mya.common.jpa.pagination.DataPage;
import mya.common.model.base.Jsonable;
import mya.mes.mdc.local.alarm.AlarmLocal;
import mya.mes.mdc.local.mongodb.FilterDto;
import mya.mes.mdc.local.mongodb.MongoDbService;
import mya.mes.mdc.local.mongodb.OperateConstant;
import mya.mes.mdc.logic.alarm.AlarmLocalImpl;
import mya.mes.mdc.model.alarm.MdcAlarm;
import mya.mes.mdc.model.alarm.MdcAlarmHis;
import mya.mes.mdc.model.alarm.MdcAlarmType;
import mya.mes.mdc.mongodb.DbCollections;
import mya.mes.mdc.mongodb.Mongo;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;

import javax.ws.rs.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Path("/{tenantId}/{loginId}/mdcalarm/ui/")
public class MdcAlarmUi {

    @PathParam("tenantId")
    private String tenantId;

    @PathParam("loginId")
    private Long loginId;

    @GET
    @Path("queryMdcAlarm/")
    @Produces({"application/json"})
    public ListResult queryMdcAlarm(
            @QueryParam("q") String qParam,
            @QueryParam("filter") final String filterParam,
            @QueryParam("sort") final String sortParam,
            @QueryParam("start") final Integer start,
            @QueryParam("limit") final Integer limit) {

        OpGet opGet = new OpGet(tenantId, loginId);

        opGet.jsonCallback(new JsonCallback<MdcAlarm>() {
            @Override
            public ObjectNode putValues(ServiceContext serviceContext, ObjectNode objectNode, MdcAlarm mdcAlarm) throws Exception {

                if(mdcAlarm.getAlarmTypeId()!=null){

                    MdcAlarmType alarmType = serviceContext.em.find(MdcAlarmType.class,mdcAlarm.getAlarmTypeId());

                    objectNode.putPOJO("alarmType",alarmType);
                }

                return objectNode;
            }
        });
        return opGet.result(MdcAlarm.class.getSimpleName(), qParam, filterParam, sortParam, start, limit);
    }

    @GET
    @Path("queryMdcAlarmHis/")
    @Produces({"application/json"})
    public ListResult queryMdcAlarmHis(
            @QueryParam("q") String qParam,
            @QueryParam("filter") final String filterParam,
            @QueryParam("sort") final String sortParam,
            @QueryParam("start") final Integer start,
            @QueryParam("limit") final Integer limit) {
        OpGet opGet = new OpGet(tenantId, loginId);
        opGet.jsonCallback(new JsonCallback<MdcAlarmHis>() {
            @Override
            public ObjectNode putValues(ServiceContext serviceContext, ObjectNode objectNode, MdcAlarmHis mdcAlarm) throws Exception {
                if (mdcAlarm.getAlarmTypeId() != null) {
                    MdcAlarmType alarmType = serviceContext.em.find(MdcAlarmType.class, mdcAlarm.getAlarmTypeId());
                    objectNode.putPOJO("alarmType", alarmType);
                }
                return objectNode;
            }
        });
        String filter = "";
        if(StringUtils.isNotBlank(filterParam)){
            filter = filterParam.replace("endDate","alarmDate");
        }
        return opGet.result(MdcAlarmHis.class.getSimpleName(), qParam, filter, sortParam, start, limit);
    }


    @GET
    @Path("queryMdcAlarmChart/{type}/{startDate}/{endDate}")
    @Produces({"application/json"})
    public ListResult queryMdcAlarmChart(
            @PathParam("type") final Integer type,
            @PathParam("startDate") final String startDate,
            @PathParam("endDate") final String endDate
    ) {
        AbstractQuery query = new AbstractQuery(tenantId,loginId) {
            @Override
            protected DataPage process(ServiceContext serviceContext) throws Exception {
                AlarmLocal service = new AlarmLocalImpl();
                List list = service.queryAlarmChart(serviceContext,type,startDate,endDate);
                return DataPage.buildFromList(list);
            }
        };
        return ListResult.result(query);
    }

    @GET
    @Path("queryMdcAlarmHis_/")
    @Produces({"application/json"})
    public Map queryMdcAlarmHis_(
            @QueryParam("q") String qParam,
            @QueryParam("filter") final String filterParam,
            @QueryParam("sort") final String sortParam,
            @QueryParam("start") final Integer start,
            @QueryParam("page") final Integer page,
            @QueryParam("limit") final Integer limit) {
        MongoDbService mongoDbService = Mongo.getInstance().getMongoDbService();
        List<FilterDto> filterDtoList = new ArrayList<FilterDto>();
        String filter = "";
        JSONArray jsonArray = null;
        if(StringUtils.isNotBlank(filterParam)){
            filter = filterParam.replace("endDate","alarmDate");
            jsonArray = JSON.parseArray(filter);
        }
        if(jsonArray != null && jsonArray.size() > 0){
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                FilterDto filterDto = new FilterDto();
                filterDto.setPropertyName(jsonObject.getString("property"));
                filterDto.setValue(jsonObject.getString("value"));
                if(">=".equals(jsonObject.getString("operator"))){
                    filterDto.setOperateType(OperateConstant.gte);
                }else if("<=".equals(jsonObject.getString("operator"))){
                    filterDto.setOperateType(OperateConstant.lte);
                }else{
                }
                filterDtoList.add(filterDto);
            }
        }
        Map pageMap = mongoDbService.queryPage(DbCollections.COL_ALARM,page,limit,filterDtoList,sortParam);
        Double count = (Double) pageMap.get("total");
        Integer total = count.intValue();
        List<Document> list = (List<Document>) pageMap.get("data");
        Map map = new HashMap<>();
        map.put("success",true);
        map.put("total",total);
        map.put("data",list);
        return map;
    }
}
